In this project, you'll use generative adversarial networks to generate new images of faces.
You'll be using two datasets in this project:
Since the celebA dataset is complex and you're doing GANs in a project for the first time, we want you to test your neural network on MNIST before CelebA. Running the GANs on MNIST will allow you to see how well your model trains sooner.
If you're using FloydHub, set data_dir to "/input" and use the FloydHub data ID "R5KrjnANiKVhLWAkpXhNBe".
data_dir = './data'
# FloydHub - Use with data ID "R5KrjnANiKVhLWAkpXhNBe"
#data_dir = '/input'
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import helper
helper.download_extract('mnist', data_dir)
helper.download_extract('celeba', data_dir)
show_n_images = 25
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
%matplotlib inline
import os
from glob import glob
from matplotlib import pyplot
mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'mnist/*.jpg'))[:show_n_images], 28, 28, 'L')
pyplot.imshow(helper.images_square_grid(mnist_images, 'L'), cmap='gray')
The CelebFaces Attributes Dataset (CelebA) dataset contains over 200,000 celebrity images with annotations. Since you're going to be generating faces, you won't need the annotations. You can view the first number of examples by changing show_n_images.
show_n_images = 25
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'img_align_celeba/*.jpg'))[:show_n_images], 28, 28, 'RGB')
pyplot.imshow(helper.images_square_grid(mnist_images, 'RGB'))
Since the project's main focus is on building the GANs, we'll preprocess the data for you. The values of the MNIST and CelebA dataset will be in the range of -0.5 to 0.5 of 28x28 dimensional images. The CelebA images will be cropped to remove parts of the image that don't include a face, then resized down to 28x28.
The MNIST images are black and white images with a single color channel while the CelebA images have 3 color channels (RGB color channel).
You'll build the components necessary to build a GANs by implementing the following functions below:
model_inputsdiscriminatorgeneratormodel_lossmodel_opttrainThis will check to make sure you have the correct version of TensorFlow and access to a GPU
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
from distutils.version import LooseVersion
import warnings
import tensorflow as tf
# Check TensorFlow Version
assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer. You are using {}'.format(tf.__version__)
print('TensorFlow Version: {}'.format(tf.__version__))
# Check for a GPU
if not tf.test.gpu_device_name():
warnings.warn('No GPU found. Please use a GPU to train your neural network.')
else:
print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))
Implement the model_inputs function to create TF Placeholders for the Neural Network. It should create the following placeholders:
image_width, image_height, and image_channels.z_dim.Return the placeholders in the following the tuple (tensor of real input images, tensor of z data)
import problem_unittests as tests
def model_inputs(image_width, image_height, image_channels, z_dim):
"""
Create the model inputs
:param image_width: The input image width
:param image_height: The input image height
:param image_channels: The number of image channels
:param z_dim: The dimension of Z
:return: Tuple of (tensor of real input images, tensor of z data, learning rate)
"""
# TODO: Implement Function
input_real = tf.placeholder(tf.float32, (None, image_width,image_height, image_channels), name="input_real")
input_z = tf.placeholder(tf.float32, (None, z_dim), name="input_z")
learning_rate = tf.placeholder(tf.float32, name="learning_rate")
return input_real, input_z, learning_rate
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_inputs(model_inputs)
Implement discriminator to create a discriminator neural network that discriminates on images. This function should be able to reuse the variables in the neural network. Use tf.variable_scope with a scope name of "discriminator" to allow the variables to be reused. The function should return a tuple of (tensor output of the discriminator, tensor logits of the discriminator).
def leaky_relu(x, alpha=0.2):
return tf.maximum(alpha * x, x)
def discriminator(images, reuse=False):
"""
Create the discriminator network
:param images: Tensor of input image(s)
:param reuse: Boolean if the weights should be reused
:return: Tuple of (tensor output of the discriminator, tensor logits of the discriminator)
"""
with tf.variable_scope('discriminator', reuse=reuse):
alpha=0.2
#Input 28x28x3
conv1 = tf.layers.conv2d(inputs=images,
filters=64,
kernel_size=3,
strides=2,
padding='same')
'''
first layer doesn't use batch normalization because we've already
normalized the input images
'''
activ1 = leaky_relu(conv1, alpha)
#layer 1 output is 14 x 14 x 64
conv2 = tf.layers.conv2d(inputs=activ1,
filters=128,
kernel_size=3,
strides=2,
padding='same')
norm2 = tf.layers.batch_normalization(inputs=conv2, training=True)
activ2 = leaky_relu(norm2, alpha)
#layer 2 output is 7 x 7 x 128
conv3 = tf.layers.conv2d(inputs=activ2,
filters=256,
kernel_size=3,
strides=1,
padding='same')
norm3 = tf.layers.batch_normalization(inputs=conv3, training=True)
activ3 = leaky_relu(norm3, alpha)
#layer 3 output is 7 x 7 x 256
'''
flatten tensor to one row, columns equals num of elements in 3rd conv layer,
which is 7 * 7 * 256;
Technically, the first dimension will be more than one row
because we're passing in batches of more than one image,
so the first dimension should equal the batch size
'''
flat = tf.reshape(tensor=activ3, shape=[-1,7*7*256])
#fully connected layer outputs just 1 scalar, 1 for real images, 0 for fake images
logits = tf.layers.dense(inputs=flat, units=1)
out = tf.sigmoid(logits)
'''
return both the 'out' prediction and the logits
before applying activation.
This is because when we apply cross entropy, it's more efficient
to combine it with the sigmoid activation, so we'll use a function
that combines both in one function:
tf.nn.sigmoid_cross_entropy_with_logits
'''
return out, logits
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_discriminator(discriminator, tf)
Implement generator to generate an image using z. This function should be able to reuse the variables in the neural network. Use tf.variable_scope with a scope name of "generator" to allow the variables to be reused. The function should return the generated 28 x 28 x out_channel_dim images.
def generator(z, out_channel_dim, is_train=True):
"""
Create the generator network
:param z: Input z
:param out_channel_dim: The number of channels in the output image
:param is_train: Boolean if generator is being used for training
:return: The tensor output of the generator
"""
'''
When we are training, we do not reuse the variables; we start with fresh random variables.
When we are not training, but testing, we want to re-use the variable and weights
that were found previously during training.
'''
reuse = not is_train
alpha=0.2
with tf.variable_scope('generator', reuse=reuse):
'''
Start by passing the input noise thru fully connected layer,
so that we can start with the desired number of units
'''
dense1 = tf.layers.dense(inputs=z, units=7*7*512)
#create first conv layer: batch size x width x height x channels
conv1 = tf.reshape(tensor=dense1, shape=[-1,7,7,512])
norm1 = tf.layers.batch_normalization(inputs=conv1, training=is_train)
activ1 = leaky_relu(norm1, alpha)
#size: 7 x 7 x 512
'''
up-sampling to increase width and height
Convolution transpose increases the width and height of output
by a factor of stride size.
'''
conv2 = tf.layers.conv2d_transpose(inputs=activ1,
filters=256,
kernel_size=3,
strides=2,
padding='same')
norm2 = tf.layers.batch_normalization(inputs=conv2, training=is_train)
activ2 = leaky_relu(norm2, alpha)
#size: 14 x 14 x 256
conv3 = tf.layers.conv2d_transpose(inputs=activ2,
filters=128,
kernel_size=3,
strides=2,
padding='same')
norm3 = tf.layers.batch_normalization(inputs=conv3, training=is_train)
activ3 = leaky_relu(norm3, alpha)
#size 28 x 28 x 128
#output layer (filters should be 3, for rgb channels)
logits = tf.layers.conv2d_transpose(inputs=activ3,
filters=out_channel_dim,
kernel_size=3,
strides=1,
padding='same')
#size: 28 x 28 x 3: same shape as the real images
#output ranges from -1 to 1, so use tanh
out = tf.tanh(logits)
return out
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_generator(generator, tf)
Implement model_loss to build the GANs for training and calculate the loss. The function should return a tuple of (discriminator loss, generator loss). Use the following functions you implemented:
discriminator(images, reuse=False)generator(z, out_channel_dim, is_train=True)def model_loss(input_real, input_z, out_channel_dim):
"""
Get the loss for the discriminator and generator
:param input_real: Images from the real dataset
:param input_z: Z input
:param out_channel_dim: The number of channels in the output image
:return: A tuple of (discriminator loss, generator loss)
"""
'''
The generator is training, and does not reuse the variables (starts with fresh weights)
The discriminator views real images and does not reuse variables.
The discriminator views fake images and reuses variables that are being used when training on real images
'''
g_model = generator(z=input_z,
out_channel_dim=out_channel_dim,
is_train=True)
d_model_real, d_logits_real = discriminator(images=input_real, reuse=False)
d_model_fake, d_logits_fake = discriminator(images=g_model, reuse=True)
'''
We can use sigmoid and not softmax here because it's just a single unit output
between 0 and 1; softmax would give us the same thing, but it's only needed when there
are more than one classes (output units), because we want all the outputs to sum to 100%
For generator, its goal is to make its fake output be labeled as ones (as real images).
For the discriminator, its goal is to label real images as 1, and generator images as 0.
For real images, labels should be ones. d_model_real and d_logits_real have the same shape,
so we can use either to create the labels; it's more clear to use d_model_real, because it's
the sigmoid output between 0 and 1, and the labels should also be between 0 and 1
'''
g_loss = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, labels=tf.ones_like(d_model_fake))
)
d_loss_real = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_real, labels=tf.ones_like(d_model_real)))
d_loss_fake = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, labels=tf.zeros_like(d_model_fake)))
d_loss = d_loss_real + d_loss_fake
return d_loss, g_loss
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_loss(model_loss)
Implement model_opt to create the optimization operations for the GANs. Use tf.trainable_variables to get all the trainable variables. Filter the variables with names that are in the discriminator and generator scope names. The function should return a tuple of (discriminator training operation, generator training operation).
def model_opt(d_loss, g_loss, learning_rate, beta1):
"""
Get optimization operations
:param d_loss: Discriminator loss Tensor
:param g_loss: Generator loss Tensor
:param learning_rate: Learning Rate Placeholder
:param beta1: The exponential decay rate for the 1st moment in the optimizer
:return: A tuple of (discriminator training operation, generator training operation)
"""
'''
We want the discriminator's optimizer to only train the discriminator variables,
likewise, the generator optimizer only modifies the generator variables
'''
tvars = tf.trainable_variables()
d_vars = [var for var in tvars if var.name.startswith('discriminator')]
g_vars = [var for var in tvars if var.name.startswith('generator')]
'''
Use control_dependencies so that batch normalization can update their population statistics.
'''
with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):
d_train_opt = tf.train.AdamOptimizer(learning_rate=learning_rate,
beta1=beta1).minimize(d_loss, var_list=d_vars)
g_train_opt = tf.train.AdamOptimizer(learning_rate=learning_rate,
beta1=beta1).minimize(g_loss, var_list=g_vars)
return d_train_opt, g_train_opt
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_opt(model_opt, tf)
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import numpy as np
def show_generator_output(sess, n_images, input_z, out_channel_dim, image_mode):
"""
Show example output for the generator
:param sess: TensorFlow session
:param n_images: Number of Images to display
:param input_z: Input Z Tensor
:param out_channel_dim: The number of channels in the output image
:param image_mode: The mode to use for images ("RGB" or "L")
"""
cmap = None if image_mode == 'RGB' else 'gray'
z_dim = input_z.get_shape().as_list()[-1]
example_z = np.random.uniform(-1, 1, size=[n_images, z_dim])
samples = sess.run(
generator(input_z, out_channel_dim, False),
feed_dict={input_z: example_z})
images_grid = helper.images_square_grid(samples, image_mode)
pyplot.imshow(images_grid, cmap=cmap)
pyplot.show()
Implement train to build and train the GANs. Use the following functions you implemented:
model_inputs(image_width, image_height, image_channels, z_dim)model_loss(input_real, input_z, out_channel_dim)model_opt(d_loss, g_loss, learning_rate, beta1)Use the show_generator_output to show generator output while you train. Running show_generator_output for every batch will drastically increase training time and increase the size of the notebook. It's recommended to print the generator output every 100 batches.
class GAN:
def __init__(self, real_size, z_size, learning_rate, alpha=0.2, beta1=0.5):
tf.reset_default_graph()
#model_inputs(image_width, image_height, image_channels, z_dim)
self.input_real, self.input_z, learning_rate_ = model_inputs(image_width=real_size[0],image_height=real_size[1],image_channels=real_size[2],z_dim=z_size)
#model_loss(input_real, input_z, out_channel_dim)
self.d_loss, self.g_loss = model_loss(input_real=self.input_real,
input_z=self.input_z,
out_channel_dim=real_size[2])
#model_opt(d_loss, g_loss, learning_rate, beta1)
self.d_opt, self.g_opt = model_opt(d_loss=self.d_loss,
g_loss=self.g_loss,
learning_rate=learning_rate,
beta1=beta1)
And another function we can use to train our network. Notice when we call generator to create the samples to display, we set training to False. That's so the batch normalization layers will use the population statistics rather than the batch statistics. Also notice that we set the net.input_real placeholder when we run the generator's optimizer. The generator doesn't actually use it, but we'd get an error without it because of the tf.control_dependencies block we created in model_opt.
def train(gan, epoch_count, batch_size, z_dim, learning_rate, beta1, get_batches, data_shape, data_image_mode):
"""
Train the GAN
:param epoch_count: Number of epochs
:param batch_size: Batch Size
:param z_dim: Z dimension
:param learning_rate: Learning Rate
:param beta1: The exponential decay rate for the 1st moment in the optimizer
:param get_batches: Function to get batches
:param data_shape: Shape of the data
:param data_image_mode: The image mode to use for images ("RGB" or "L")
"""
'''
re-use the same generator input when checking the progress of training with sample output images
data_shape for mnist looks like:
(60000, 28, 28, 1)
batch_size, width, height, channels
use data_shape[3] to get the channel size
'''
sample_z = np.random.uniform(-1, 1, size=(72, z_dim))
samples, losses = [], []
steps=0
n_images = 12 # num of generated images to show when checking progress
out_channel_dim = data_shape[3]
print_every=10
show_every=20
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
saver = tf.train.Saver()
for epoch_i in range(epoch_count):
for batch_images in get_batches(batch_size):
steps +=1
#input for generator
batch_z = np.random.uniform(-1, 1, size=(batch_size, z_dim))
#optimizers
'''
Also notice that we set the `net.input_real` placeholder when we run the generator's optimizer.
The generator doesn't actually use it,
but we'd get an error without it because of the `tf.control_dependencies` block
we created in `model_opt`.
'''
_ = sess.run(gan.d_opt, feed_dict={gan.input_real: batch_images, gan.input_z: batch_z})
_ = sess.run(gan.g_opt, feed_dict={gan.input_z: batch_z, gan.input_real: batch_images})
if steps % print_every == 0:
train_loss_d = sess.run(gan.d_loss, feed_dict={gan.input_z: batch_z, gan.input_real: batch_images})
train_loss_g = sess.run(gan.g_loss, feed_dict={gan.input_z: batch_z})
print("Epoch {}/{}".format(epoch_i+1, epoch_count),
"Discriminator loss {:.4f}".format(train_loss_d),
"Generator loss {:.4f}".format(train_loss_g))
losses.append((train_loss_d,train_loss_g))
if steps % show_every == 0:
show_generator_output(sess=sess,
n_images=n_images,
input_z=gan.input_z,
out_channel_dim=out_channel_dim,
image_mode=data_image_mode)
saver.save(sess, "./checkpoints/generator.ckpt")
with open("samples.pkl", "wb") as f:
pkl.dump(samples,f)
return losses, samples
Test your GANs architecture on MNIST. After 2 epochs, the GANs should be able to generate images that look like handwritten digits. Make sure the loss of the generator is lower than the loss of the discriminator or close to 0.
batch_size = 128
epochs = 25
learning_rate = 0.0002
real_size = (28,28,1)
z_dim = 100
alpha = 0.2
beta1 = 0.5
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
epochs = 2
mnist_dataset = helper.Dataset('mnist', glob(os.path.join(data_dir, 'mnist/*.jpg')))
with tf.Graph().as_default():
gan = GAN(real_size=real_size, z_size=z_dim, learning_rate=learning_rate, alpha=alpha, beta1=beta1)
train(gan,epochs, batch_size, z_dim, learning_rate, beta1, mnist_dataset.get_batches,
mnist_dataset.shape, mnist_dataset.image_mode)
Run your GANs on CelebA. It will take around 20 minutes on the average GPU to run one epoch. You can run the whole epoch or stop when it starts to generate realistic faces.
batch_size = 128
z_dim = 100
learning_rate = 0.0002
alpha = 0.2
beta1 = 0.5
real_size = (28,28,3)
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
epochs = 1
celeba_dataset = helper.Dataset('celeba', glob(os.path.join(data_dir, 'img_align_celeba/*.jpg')))
with tf.Graph().as_default():
gan = GAN(real_size=real_size, z_size=z_dim, learning_rate=learning_rate, alpha=alpha, beta1=beta1)
train(gan,epochs, batch_size, z_dim, learning_rate, beta1, celeba_dataset.get_batches,
celeba_dataset.shape, celeba_dataset.image_mode)
When submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as "dlnd_face_generation.ipynb" and save it as a HTML file under "File" -> "Download as". Include the "helper.py" and "problem_unittests.py" files in your submission.